// JavaScript Document
var host = "http://www.hungarianexporters.hu";

var timer = null;
var iv = null;
var counter = 0;
var busy = false;
var testtime = 0;

var calls = {};

var statistics = [];

var words = [
     "fish",
     "milk",
     "wheat",
     "food",
     "meet",
     "swine",
     "coffee",
     "fur"
];

var users = {};

function startTest() {
    var available = [];
    if (jQuery("[type='checkbox'][id='search_expimp']").attr("checked") == "checked") { available.push({type : "expimp"}); }
    if (jQuery("[type='checkbox'][id='search_businessleads']").attr("checked") == "checked") { available.push({ type : "businessleads"}); }
    if (jQuery("[type='checkbox'][id='search_services']").attr("checked")) { available.push({ type : "services" }); }
    if (jQuery("[type='checkbox'][id='search_habroad']").attr("checked")) { available.push({ type : "habroad" }); }

    var usercount =  parseInt(jQuery("input[name='usercount']").val(), 10);
    var time = parseInt(jQuery("input[name='time']").val(), 10) * 60*1000;
    testtime = time;

    for (var i = 0; i < usercount; i++) {
        startUser("user_" + (i+1), available);
    }
    busy = true;
    jQuery("div#progress_container").show("fade", {}, 400);
    iv = setInterval(function() {
        counter++;
        var newvalue = counter / (time/1000) * 100;
        jQuery("div#progressbar").progressbar("value", newvalue);
    }, 1000);
    timer = setTimeout(function() {
        stopTest();
    }, time);
    for (var i = 0; i < usercount; i++) {
        callNextUrl("user_" + (i+1));
    }
}

function startUser(userId, availablePages) {
    users[userId] = {
        urlCount : 0
    };
    calls[userId] = [];
    for (var i = 0; i < Math.ceil(testtime/100); i++) {
        var possibility = Math.ceil(Math.random() * 100);
        var ndx = possibility % availablePages.length;
        if (availablePages[ndx].type == "expimp") {
            var poss2 = Math.ceil(Math.random() * 100);
            var bucket = poss2 % 3;
            if (bucket == 0) {
                var hscode = Math.ceil(Math.random() * 9000);
                calls[userId].push(generateUrlForExport("hs4", {hs4 : hscode}));
            } else if (bucket == 1) {
                var poss3 = Math.ceil(Math.random() * 100);
                var buck3 = poss3 % words.length;
                calls[userId].push(generateUrlForExport("freetext", { freetext : words[buck3]}));
            } else {
                var item = Math.ceil(Math.random() * 500);
                calls[userId].push(generateUrlForExport("company", { selectedItem : item}));
            }
        } else if (availablePages[ndx].type == "businessleads") {
            var poss2 = Math.ceil(Math.random() * 100);
            if (poss2 % 2 == 0) { calls[userId].push(generateUrlForBusinesslead("sell")); }
            else { calls[userId].push(generateUrlForBusinesslead("buy")); }
        } else if (availablePages[ndx].type == "services") {
            var poss2 = Math.ceil(Math.random() * 100);
            var serviceType = poss2 % 29 + 1;
            calls[userId].push(generateUrlForServices(serviceType));
        } else if (availablePages[ndx].type == "habroad") {
            var poss2 = Math.ceil(Math.random() * 100);
            var bucket = poss2 % 3;
            if (bucket == 0) {
                var hscode = Math.ceil(Math.random() * 9000);
                calls[userId].push(generateUrlForHungarianAbroad("country", {selected : "United Kingdom"}));
            } else if (bucket == 1) {
                var poss3 = Math.ceil(Math.random() * 100);
                var buck3 = poss3 % words.length;
                calls[userId].push(generateUrlForHungarianAbroad("company", { selected : Math.ceil(Math.random() * 10)}));
            }
        }
    }
}

function callNextUrl(userId) {
    var d = new Date();
    var url = host + "?" + calls[userId][users[userId].urlCount];
    users[userId].urlCount++;
    statistics.push({
        url : url,
        user : userId,
        startTime : d.getTime()
    });
    startSearch(url, statistics.length-1, function() {
        callNextUrl(userId);
    });
}

function startSearch(url, statPos, doAfter) {
    jQuery.ajax(url, {
        type : "get",
        dataType : "html",
        success : function() {
            if (busy) {
                var d = new Date();
                statistics[statPos]['finishTime'] = d.getTime();
                doAfter();
            }
        }
    });
}

function stopTest() {
    clearInterval(iv);
    busy = false;
    var avg = 0;
    var min = 10000000;
    var max = 0;
    for (var i = 0; i < statistics.length; i++) {
        var t = statistics[i].finishTime - statistics[i].startTime;
        if (t < min) { min = t; }
        if (t > max) { max = t; }
        if (!isNaN(t)) {
            avg += t;
        }
    }
    avg = avg / statistics.length;
    jQuery("div#testresult_container").show("fade", {}, 400);
    jQuery("input[name='avgtime']").val(avg);
    jQuery("input[name='shortest']").val(min);
    jQuery("input[name='longest']").val(max);
}

function generateUrlForExport(type, typeParams) {
    var url = "choice=list_exportproducts";
    if (type == "freetext") {
        url += "&params=" + encodeURIComponent(serialize({
            freetext : typeParams['freetext'],
            enteredText : typeParams['freetext']
        }));
    } else if (type == "company") {
        url += "&params=" + encodeURIComponent(serialize({
            selectedItem : typeParams['selectedItem']
        }));
    } else if (type == "hs4") {
        url += "&params=" + encodeURIComponent(serialize({
            hs4 : typeParams['hs4'],
            hs2 : typeParams['hs4'],
            enteredText : typeParams['hs4']
        }));
    }
    return url;
}

function generateUrlForImport(type, typeParams) {
    var url = "choice=list_importproducts";
    if (type == "freetext") {
        url += "&params=" + encodeURIComponent(serialize({
            freetext : typeParams['freetext'],
            enteredText : typeParams['freetext']
        }));
    } else if (type == "company") {
        url += "&params=" + encodeURIComponent(serialize({
            selectedItem : typeParams['selectedItem']
        }));
    } else if (type == "hs4") {
        url += "&params=" + encodeURIComponent(serialize({
            hs4 : typeParams['hs4'],
            hs2 : typeParams['hs4'],
            enteredText : typeParams['hs4']
        }));
    }
    return url;
}

function generateUrlForBusinesslead(type) {
    var url = "choice=list_businessleads&";
    url += "params=" + encodeURIComponent(serialize({
        type : type
    }));
    return url;
}

function generateUrlForServices(service) {
    var url = "choice=list_services&";
    url += "params=" + serialize({
        selectedService : service
    });
    return url;
}

function generateUrlForHungarianAbroad(type, typeParams) {
    var url = "choice=list_hacompanies&";
    if (type == "country") {
        url += "params=" + encodeURIComponent(serialize({
            type : type,
            selectedItem : typeParams['selected'],
            enteredText : typeParams['selected']
        }));
    } else if (type == "company") {
        url += "params=" + encodeURIComponent(serialize({
            type : type,
            selectedItem : typeParams['selected'],
            enteredText : typeParams['selected']
        }));
    }
    return url;
}

function serialize(data) {
    var params2 = [];
    for (var fld in data) {
        if (typeof data[fld] == "function") { continue; }
        params2.push("s:" + fld.length + ":\"" + fld + "\";s:" + ("" + data[fld]).length + ":\"" + data[fld] + "\";");
    }
    return "a:" + params2.length + ":{" + params2.join("") + "}";
}
